package com.ysx.wemedia.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysx.common.constants.BusinessConstants;
import com.ysx.common.pojo.PageInfo;
import com.ysx.common.pojo.PageRequestDto;
import com.ysx.common.pojo.Result;
import com.ysx.common.utils.RequestHeaderInfoUtils;
import com.ysx.wemedia.dto.ContentNode;
import com.ysx.wemedia.dto.WmNewsDto;
import com.ysx.wemedia.dto.WmNewsDtoSubmit;
import com.ysx.wemedia.pojo.WmNews;
import com.ysx.wemedia.service.WmNewsService;
import com.ysx.wemedia.vo.WmNewsVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.Api;
import com.ysx.core.controller.AbstractCoreController;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* <p>
* 自媒体图文内容信息表 控制器</p>
* @author ljh
* @since 2021-09-08
*/
@Api(value="自媒体图文内容信息表",tags = "WmNewsController")
@RestController
@RequestMapping("/wmNews")
public class WmNewsController extends AbstractCoreController<WmNews> {

    private WmNewsService wmNewsService;

    //kafka模板对象
    @Autowired
    private KafkaTemplate kafkaTemplate;

    //注入
    @Autowired
    public WmNewsController(WmNewsService wmNewsService) {
        super(wmNewsService);
        this.wmNewsService=wmNewsService;
    }

    @PostMapping("/searchPage")
    @ApiOperation("根据请求条件，查询自媒体作品")
    public Result getPageInfo(@RequestBody PageRequestDto<WmNewsDto> pageRequestDto) {
        //获取分页条件
        Page<WmNews> wmNewsPage = new Page<>(pageRequestDto.getPage(), pageRequestDto.getSize());
        //创建条件构造器
        QueryWrapper<WmNews> wmNewsQueryWrapper = new QueryWrapper<>();
        WmNewsDto body = pageRequestDto.getBody();
        //根据不同场景追加搜索条件
        if (ObjectUtils.isNotEmpty(body)) {
            //文章状态
            if (body.getStatus() != null) {
                wmNewsQueryWrapper.eq("status", body.getStatus());
            }
            //关键字
            if (body.getTitle() != null) {
                wmNewsQueryWrapper.like("title", body.getTitle());
            }
            //频道列表
            if (body.getChannelId() != null) {
                wmNewsQueryWrapper.eq("channel_id", body.getChannelId());
            }
            //发布日期
            LocalDateTime startTime = body.getStartTime();
            LocalDateTime endTime = body.getEndTime();
            if (startTime != null && endTime == null) {
                wmNewsQueryWrapper.ge("publish_time", startTime);
            } else if (startTime == null && endTime != null) {
                wmNewsQueryWrapper.le("publish_time", endTime);
            } else if (startTime!=null&&endTime!=null){
                wmNewsQueryWrapper.between("publish_time",startTime,endTime);
            }
        }
        //自媒体文章列表 查询条件只能是当前用户的
        String headerUserId = RequestHeaderInfoUtils.getHeaderUserId();
        wmNewsQueryWrapper.eq("user_id",headerUserId);
        //调用条件构造器
        IPage<WmNews> page = wmNewsService.page(wmNewsPage, wmNewsQueryWrapper);
        PageInfo<WmNews> pageInfo = this.getPageInfo(page);
        return Result.ok(pageInfo);
    }

    @PostMapping("/searchNotPass")
    @ApiOperation("根据请求条件 查询审核失败或者人工审核自媒体素材")
    public Result getSearchNotPass(@RequestBody PageRequestDto<WmNewsDto> pageRequestDto) {

        PageInfo<WmNewsVo> pageInfo=wmNewsService.getSearchNotPass(pageRequestDto);

        return Result.ok(pageInfo);
    }

    @PutMapping("/updateWmNewsStatus/{id}")
    @ApiOperation("审核通过 或者 驳回  8 标识通过  2 标识驳")
    public Result updateWmNewsStatus(@PathVariable("id") Integer wmNewsId,Integer status) {
        //校验参数的合法性
        if (status == 8 || status == 9) {
            //根据自媒体Id查询作者Id
            WmNews wmNews=wmNewsService.getById(wmNewsId);
            //更新状态
            wmNews.setStatus(status);
            wmNewsService.updateById(wmNews);
            return Result.ok();
        } else {
            return Result.error("修改的状态有误");
        }
    }

    @PutMapping("/findWmNewsStatus/{id}")
    @ApiOperation("查看审核状态")
    public Result findWmNewsStatus(@PathVariable("id") Integer wmNewsId) {
        //select wm.*,us.id as authorName  from wm_news wm,wm_user us where wm.user_id =us.id

        //校验参数合法性
        if (wmNewsId == null) {
            return Result.error("文章Id为空");
        } else {
            //根据文章id联表查询文章信息和作者用户
            WmNewsVo wmNewsVo=wmNewsService.findWmNewsStatus(wmNewsId);

            return Result.ok( wmNewsVo);
        }
    }




    @PostMapping("/publishVmNews/{isSubmit}")
    @ApiOperation("发布自媒体文章")
    public Result publishVmNews(@RequestBody WmNewsDtoSubmit<ContentNode> wxNewsDtoSubmit, @PathVariable("isSubmit") Integer isSubmit) {
        //VmNews DB数据库对象
        //执行是否成功的标识
        boolean insertOrUpdate=false;
        //WmNewsDtoSubmit 数据库传输交互对象
        LocalDateTime localDateTime = LocalDateTime.now();
        if (Objects.isNull(wxNewsDtoSubmit)) {
            return Result.errorMessage("请以正确的格式传输,不允许空的参数出现");
        }
        WmNews wmNews = new WmNews();
        //1,拷贝公共属性到DB对象
        BeanUtils.copyProperties(wxNewsDtoSubmit,wmNews);
        //2,获取当前自媒体用户id 设置到DB对象
        String userId = RequestHeaderInfoUtils.getHeaderUserId();
        wmNews.setUserId(Integer.parseInt(userId));
        //3,设置文章主要内容
        List<ContentNode> content = wxNewsDtoSubmit.getContent();
        String contentJsonStr = JSON.toJSONString(content);
        wmNews.setContent(contentJsonStr);
        //TODO 使用String.join优化
        List<String> images = wxNewsDtoSubmit.getImages();
        if (CollectionUtils.isNotEmpty(images)) {
            wmNews.setImages(String.join(",",images));
        }
        //4,判断type类型是否为-1（自动）
        if (wxNewsDtoSubmit.getType() == -1) {
            //调用公共方法 将contentJsonStr中类型为images的属性封装到集合中
            List<String> imagesPropertiesList = getListImagesProperties(content);
            //根据集合大小进行赋值
            if (imagesPropertiesList.size() == 0) {
                wmNews.setImages(null);
                wmNews.setType(0);
            } else if (imagesPropertiesList.size() == 1) {
                wmNews.setImages(imagesPropertiesList.get(0));
                wmNews.setType(1);
            } else {
                wmNews.setImages(String.join(",",imagesPropertiesList));
                wmNews.setType(3);
            }
        }
        //判断发布时间是否为null TODO Date转成LocalDateTime
        Date publishTime = wxNewsDtoSubmit.getPublishTime();
        if (publishTime != null) {
            Timestamp timestamp = new Timestamp(publishTime.getTime());
            wmNews.setPublishTime(timestamp.toLocalDateTime());
        }
        //6,根据submit 设置提交时间
        if (isSubmit == 1) {
            wmNews.setSubmitedTime(localDateTime);
        }
        //5,根据新闻id是否存在 设置创建时间
        if (Objects.isNull(wxNewsDtoSubmit.getId())) {//没有用户id
            wmNews.setCreatedTime(localDateTime);
            insertOrUpdate = wmNewsService.save(wmNews);
        } else {
            insertOrUpdate = wmNewsService.updateById(wmNews);
        }
        //在执行结束之后 发送消息队列
        if (insertOrUpdate && isSubmit == 1&&wmNews.getId()!=null) {
            kafkaTemplate.send(BusinessConstants.MqConstants.WM_NEWS_TO_ADMIN_MQTOPIC,wmNews.getId()+"");
        }
        return Result.ok();
    }


    @ApiOperation("根据新闻ID查询记录 回显")
    @GetMapping("/one/{obtainVmNews}")
    public Result<WmNewsDtoSubmit<ContentNode>> obtainVmNewsDtoSubmit(@PathVariable("obtainVmNews")String vmNewsId) {
        try {
            //调用service 传入新闻Id 返回DTO对象
            WmNewsDtoSubmit<ContentNode> vmNewsDtoSubmit = wmNewsService.obtainVmNewsDtoSubmit(vmNewsId);
            //返回Result
            return Result.ok(vmNewsDtoSubmit);
        } catch (Exception exception) {
            return Result.errorMessage(exception.getMessage());
        }
    }

    @ApiOperation("根据文章的id删除")
    @DeleteMapping("/one/{delVmNews}")
    public Result<WmNewsDtoSubmit<ContentNode>> delVmNewsDtoSubmit(@PathVariable("delVmNews")String delVmNews) {
        try {
            //调用service 传入新闻Id 返回DTO对象
            wmNewsService.delVmNewsDtoSubmit(delVmNews);
            //返回Result
            return Result.ok();
        } catch (Exception exception) {
            return Result.errorMessage(exception.getMessage());
        }
    }

    @ApiOperation("根据文章的id上下架作品")
    @PutMapping("/one/{outVmNews}")
    public Result<WmNewsDtoSubmit<ContentNode>> outVmNewsDtoSubmit(@PathVariable("outVmNews")String outVmNews) {
        try {
            //调用service 传入新闻Id 返回DTO对象
            wmNewsService.outVmNewsDtoSubmit(outVmNews);
            //返回Result
            return Result.ok();
        } catch (Exception exception) {
            return Result.errorMessage(exception.getMessage());
        }
    }






    //Stream流方法抽取
    List<String> getListImagesProperties (List<ContentNode> content){

        List<String> list=new ArrayList<>();
        if (ObjectUtils.isEmpty(content)) {
            return list;
        }
        Stream<ContentNode> stream = content.stream();
        return stream.filter(contentNode -> contentNode.getType().equals("image"))
                .map(ContentNode::getValue)
                .collect(Collectors.toList());
    }


}

